<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Obs\ObsClient;

class ObsService
{
    /** @var ObsClient */
    private $client;

    /** @var string */
    private $bucket;

    /**
     * ObsService constructor.
     */
    public function __construct()
    {
        $this->client = new ObsClient([
            'key' => config('services.obs.ak'),
            'secret' => config('services.obs.sk'),
            'endpoint' => config('services.obs.endpoint'),
            'signature' => 'obs',
        ]);
        $this->bucket = config('services.obs.bucket');
    }

    public function upload($key, UploadedFile $file)
    {
        $key = $key . '.' . $file->extension();
        $this->client->putObject([
            'Bucket' => $this->bucket,
            'Key' => $key,
            'Body' => fopen($file, 'r'),
        ]);

        return $this->getFileUrl($key);
    }

    public function getFileUrl($key)
    {
        return sprintf(
            'https://%s/%s',
            config('services.obs.domain'),
            $key
        );
    }

    public function getClientConfig($key)
    {
        return [
            'options' => [
                'access_key_id' => config('services.obs.ak'),
                'secret_access_key' => config('services.obs.sk'),
                'server' => 'https://' . config('services.obs.endpoint'),
                'timeout' => 3600,
            ],
            'bucket' => $this->bucket,
            'key' => $key,
        ];
    }
}
